<?php

/**
 +-----------------------------------------------------
 * PublicModel
 +-----------------------------------------------------
 * @author	liuricheng 
 * @time	2014-03-13
 * @type	[add]
 * 
 */
import("ORG.Util.Function");


class CommonModel extends Model{
	
	 // 获取某个字段 的值
	 function getOne($sql, $limited = false){
        if ($limited == true){
            $sql = trim($sql . ' LIMIT 1');
        }
        $res	=	$this->query($sql);
        
       	if(empty($res)){
       		return false;
       	}
       	$res	=	array_values($res[0]);       	
       	if(empty($res[0])){
       		return '';
       	}
       	return $res[0];
    }
    
    /**
     * 获取某一列的值
     * @param $sql
     */
    function getCol($sql){
        $res 				= 	$this->query($sql);        
        if ($res !== false){
            $arr 			=	 array();
            foreach($res as $row){
            	foreach($row as $v){
            		$arr[] 	= 	$v; 
            	}           	
            }
            return $arr;
        }
        else{
            return false;
        }
    }
    
    // 获取一条记录
	function getRow($sql, $limited = false){
        if ($limited == true){
            $sql = trim($sql . ' LIMIT 1');
        }
        $res 	= 	$this->query($sql);
        if(empty($res)){
        	return false;
        }
        if(empty($res[0])){
        	return '';
        }
        return $res[0];
    }
    
	/**
	 * 插入数据
	 * Enter description here ...
	 * @param unknown_type $table --- 前面不加表前缀
	 * @param unknown_type $field_values
	 * @param unknown_type $mode
	 * @param unknown_type $where
	 * @param unknown_type $querymode
	 */
	public function autoExecute($table, $field_values, $mode = 'INSERT', $where = '', $querymode = ''){				
		$tableName		=	auto_table_name($table);		
		$field_names	=	M($tableName)->getDbFields();
		//t($field_names);
		
        $sql = '';
        if ($mode == 'INSERT'){ 
            $fields = $values = array();
            foreach ($field_names AS $value){
                if (array_key_exists($value, $field_values) == true){
                    $fields[] = $value;
                    $values[] = "'" . $field_values[$value] . "'";
                }
            }
            if (!empty($fields)){
                $sql = 'INSERT INTO ' . 'ybr_' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
            }      
        }
        else{
            $sets = array();
            foreach ($field_names AS $value)            {
                if (array_key_exists($value, $field_values) == true){
                    $sets[] = $value . " = '" . $field_values[$value] . "'";
                }
            }
            if (!empty($sets)){
                $sql = 'UPDATE ' . 'ybr_' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
            }
        }
        // 记录autoExecute 执行的sql语句 
        //Log::write(' Function  :  autoExecute ', '执行的SQL  :  ' . $sql . ' --- ' . date('Y-m-d H:i:s'));  
         
        //echo $sql;
        
        if ($sql){
        	if($this->query($sql) != false)
            	return true;
            else 
            	return false;
        }
        else{
            return false;
        }
	}
    
	public function autoQuery($table, $field_values, $mode = 'INSERT', $where = '', $querymode = ''){				
		$tableName		=	auto_table_name($table);		
		$field_names	=	M($tableName)->getDbFields();		

        $sql = '';
        if ($mode == 'INSERT'){  
			 return M($tableName)->add($field_values);
        }
        else{
			return M($tableName)->where($where)->save($field_values);
        }
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param $table
	 * @param $field_values
	 * @param $update_values
	 * @param $where
	 * @param $querymode
	 */
    function autoReplace($table, $field_values, $update_values, $where = '', $querymode = ''){
        $tableName		=	auto_table_name($table);		
		$field_names	=	M($tableName)->getDbFields();	
		$table			=	"ybr_" . $table;
		
		
        $primary_keys = array();
        foreach ($field_descs AS $value){
            $field_names[] = $value['Field'];
            if ($value['Key'] == 'PRI'){
                $primary_keys[] = $value['Field'];
            }
        }

        $fields = $values = array();
        foreach ($field_names AS $value){
            if (array_key_exists($value, $field_values) == true){
                $fields[] = $value;
                $values[] = "'" . $field_values[$value] . "'";
            }
        }

        $sets = array();
        foreach ($update_values AS $key => $value){
            if (array_key_exists($key, $field_values) == true){
                if (is_int($value) || is_float($value)){
                    $sets[] = $key . ' = ' . $key . ' + ' . $value;
                }
                else{
                    $sets[] = $key . " = '" . $value . "'";
                }
            }
        }

        $sql = '';
        if (empty($primary_keys)){
            if (!empty($fields)){
                $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
            }
        }
        else{
            if ($this->version() >= '4.1'){
                if (!empty($fields)){
                    $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
                    if (!empty($sets)){
                        $sql .=  'ON DUPLICATE KEY UPDATE ' . implode(', ', $sets);
                    }
                }
            }
            else{
                if (empty($where)){
                    $where = array();
                    foreach ($primary_keys AS $value){
                        if (is_numeric($value)){
                            $where[] = $value . ' = ' . $field_values[$value];
                        }
                        else{
                            $where[] = $value . " = '" . $field_values[$value] . "'";
                        }
                    }
                    $where = implode(' AND ', $where);
                }

                if ($where && (!empty($sets) || !empty($fields))){
                    if (intval($this->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0){
                        if (!empty($sets)){
                            $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
                        }
                    }
                    else{
                        if (!empty($fields)){
                            $sql = 'REPLACE INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
                        }
                    }
                }
            }
        }

        if ($sql){
            return $this->query($sql, $querymode);
        }
        else{
            return false;
        }
    }
    
    /**
     * 查询插入数据库的id
     * Enter description here ...
     */
    function insert_id(){
    	return mysql_insert_id();
    }
    
    
    
}